/**
 * 个人中心页面组件
 * Profile Page Component
 */

class ProfileManager {
  constructor() {
    this.currentUser = null;
    this.avatarFile = null;
    this.cropCanvas = null;
    this.cropContext = null;
    this.cropImage = null;
    this.cropData = {
      x: 0,
      y: 0,
      width: 200,
      height: 200,
      scale: 1
    };
    
    this.init();
  }

  /**
   * 初始化个人中心
   */
  init() {
    this.bindEvents();
    this.loadUserProfile();
    this.loadUserStats();
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 返回按钮
    document.getElementById('back-btn').addEventListener('click', () => {
      window.location.href = '/';
    });

    // 头像上传
    document.getElementById('avatar-upload').addEventListener('click', () => {
      document.getElementById('avatar-input').click();
    });

    document.getElementById('avatar-input').addEventListener('change', (e) => {
      this.handleAvatarSelect(e.target.files[0]);
    });

    // 编辑资料
    document.getElementById('edit-profile-btn').addEventListener('click', () => {
      this.showEditProfileModal();
    });

    // 修改密码
    document.getElementById('change-password-btn').addEventListener('click', () => {
      this.showChangePasswordModal();
    });

    // 模态框事件
    this.bindModalEvents();
    
    // 管理员功能
    this.bindAdminEvents();
  }

  /**
   * 绑定模态框事件
   */
  bindModalEvents() {
    // 编辑资料模态框
    const editModal = document.getElementById('edit-profile-modal');
    const closeEditBtn = document.getElementById('close-edit-modal');
    const cancelEditBtn = document.getElementById('cancel-edit-btn');
    const saveProfileBtn = document.getElementById('save-profile-btn');

    [closeEditBtn, cancelEditBtn].forEach(btn => {
      btn.addEventListener('click', () => {
        this.hideEditProfileModal();
      });
    });

    saveProfileBtn.addEventListener('click', () => {
      this.saveProfile();
    });

    // 修改密码模态框
    const passwordModal = document.getElementById('change-password-modal');
    const closePasswordBtn = document.getElementById('close-password-modal');
    const cancelPasswordBtn = document.getElementById('cancel-password-btn');
    const savePasswordBtn = document.getElementById('save-password-btn');

    [closePasswordBtn, cancelPasswordBtn].forEach(btn => {
      btn.addEventListener('click', () => {
        this.hideChangePasswordModal();
      });
    });

    savePasswordBtn.addEventListener('click', () => {
      this.changePassword();
    });

    // 头像裁剪模态框
    this.bindCropModalEvents();
  }

  /**
   * 绑定头像裁剪模态框事件
   */
  bindCropModalEvents() {
    const cropModal = document.getElementById('avatar-crop-modal');
    const closeCropBtn = document.getElementById('close-crop-modal');
    const cancelCropBtn = document.getElementById('cancel-crop-btn');
    const saveAvatarBtn = document.getElementById('save-avatar-btn');
    const zoomSlider = document.getElementById('crop-zoom');
    const zoomInBtn = document.getElementById('crop-zoom-in');
    const zoomOutBtn = document.getElementById('crop-zoom-out');

    [closeCropBtn, cancelCropBtn].forEach(btn => {
      btn.addEventListener('click', () => {
        this.hideCropModal();
      });
    });

    saveAvatarBtn.addEventListener('click', () => {
      this.saveAvatar();
    });

    zoomSlider.addEventListener('input', (e) => {
      this.updateCropScale(parseFloat(e.target.value));
    });

    zoomInBtn.addEventListener('click', () => {
      const currentValue = parseFloat(zoomSlider.value);
      const newValue = Math.min(3, currentValue + 0.1);
      zoomSlider.value = newValue;
      this.updateCropScale(newValue);
    });

    zoomOutBtn.addEventListener('click', () => {
      const currentValue = parseFloat(zoomSlider.value);
      const newValue = Math.max(0.5, currentValue - 0.1);
      zoomSlider.value = newValue;
      this.updateCropScale(newValue);
    });

    // 初始化裁剪画布
    this.initCropCanvas();
  }

  /**
   * 绑定管理员功能事件
   */
  bindAdminEvents() {
    // 创建用户
    document.getElementById('create-user-btn').addEventListener('click', () => {
      this.showCreateUserModal();
    });

    // 刷新用户列表
    document.getElementById('refresh-users-btn').addEventListener('click', () => {
      this.loadUsersList();
    });

    // 用户搜索
    document.getElementById('user-search').addEventListener('input', (e) => {
      this.filterUsers(e.target.value);
    });

    // 绑定用户管理模态框事件
    this.bindUserManagementModals();
  }

  /**
   * 加载用户资料
   */
  async loadUserProfile() {
    try {
      this.showLoading();
      
      const response = await api.get('/user/profile');
      this.currentUser = response.user;
      
      this.updateUserDisplay();
      this.updateStorageDisplay(response.storageUsed, response.user.storage_limit);
      
      // 显示管理员功能
      if (response.user.role === 'admin') {
        document.getElementById('admin-section').classList.remove('hidden');
        // 加载用户列表和系统统计
        this.loadUsersList();
      }
      
    } catch (error) {
      console.error('加载用户资料失败:', error);
      notification.error('加载用户资料失败');
    } finally {
      this.hideLoading();
    }
  }

  /**
   * 加载用户统计信息
   */
  async loadUserStats() {
    try {
      const [notesResponse, filesResponse] = await Promise.all([
        api.get('/notes?limit=1'),
        api.get('/files?limit=1')
      ]);
      
      document.getElementById('notes-count').textContent = notesResponse.total || 0;
      document.getElementById('files-count').textContent = filesResponse.total || 0;
      
    } catch (error) {
      console.error('加载统计信息失败:', error);
    }
  }

  /**
   * 更新用户显示
   */
  updateUserDisplay() {
    if (!this.currentUser) return;

    // 更新头部信息
    document.getElementById('header-user-name').textContent = this.currentUser.nickname;
    document.getElementById('header-user-email').textContent = this.currentUser.email;

    // 更新主要信息
    document.getElementById('user-name').textContent = this.currentUser.nickname;
    document.getElementById('user-email').textContent = this.currentUser.email;
    document.getElementById('user-role').textContent = this.currentUser.role === 'admin' ? '管理员' : '用户';
    
    // 更新加入日期
    const joinDate = new Date(this.currentUser.created_at);
    document.getElementById('user-join-date').textContent = `加入于 ${joinDate.toLocaleDateString('zh-CN')}`;

    // 更新头像
    this.updateAvatarDisplay();
  }

  /**
   * 更新头像显示
   */
  updateAvatarDisplay() {
    const avatarElements = [
      document.getElementById('user-avatar'),
      document.getElementById('header-user-avatar')
    ];

    avatarElements.forEach(element => {
      if (this.currentUser.avatar) {
        element.innerHTML = `<img src="${this.currentUser.avatar}" alt="头像" class="w-full h-full object-cover rounded-full">`;
      } else {
        element.innerHTML = '<i class="fa fa-user text-neutral-500 text-2xl"></i>';
      }
    });
  }

  /**
   * 更新存储显示
   */
  updateStorageDisplay(used, limit) {
    const usedBytes = used || 0;
    const limitBytes = limit || 0;
    const percentage = limitBytes > 0 ? (usedBytes / limitBytes) * 100 : 0;

    document.getElementById('storage-used').textContent = this.formatFileSize(usedBytes);
    document.getElementById('storage-limit').textContent = this.formatFileSize(limitBytes);
    document.getElementById('storage-text').textContent = `${this.formatFileSize(usedBytes)} / ${this.formatFileSize(limitBytes)} (${percentage.toFixed(1)}%)`;
    
    const fillElement = document.getElementById('storage-fill');
    fillElement.style.width = `${Math.min(percentage, 100)}%`;
    
    // 根据使用率改变颜色
    if (percentage >= 90) {
      fillElement.className = 'storage-fill bg-danger';
    } else if (percentage >= 80) {
      fillElement.className = 'storage-fill bg-warning';
    } else {
      fillElement.className = 'storage-fill bg-primary';
    }
  }

  /**
   * 显示编辑资料模态框
   */
  showEditProfileModal() {
    if (!this.currentUser) return;

    document.getElementById('edit-nickname').value = this.currentUser.nickname;
    document.getElementById('edit-email').value = this.currentUser.email;
    document.getElementById('edit-profile-modal').classList.remove('hidden');
  }

  /**
   * 隐藏编辑资料模态框
   */
  hideEditProfileModal() {
    document.getElementById('edit-profile-modal').classList.add('hidden');
  }

  /**
   * 保存个人资料
   */
  async saveProfile() {
    const nickname = document.getElementById('edit-nickname').value.trim();
    
    if (!nickname) {
      notification.warning('请输入昵称');
      return;
    }

    if (nickname.length > 50) {
      notification.warning('昵称不能超过50个字符');
      return;
    }

    try {
      const response = await api.put('/user/profile', {
        nickname: nickname
      });

      if (response.success) {
        this.currentUser.nickname = nickname;
        this.updateUserDisplay();
        this.hideEditProfileModal();
        notification.success('个人资料更新成功');
      } else {
        notification.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('保存个人资料失败:', error);
      notification.error('保存个人资料失败');
    }
  }

  /**
   * 显示修改密码模态框
   */
  showChangePasswordModal() {
    // 清空表单
    document.getElementById('current-password').value = '';
    document.getElementById('new-password').value = '';
    document.getElementById('confirm-password').value = '';
    document.getElementById('change-password-modal').classList.remove('hidden');
  }

  /**
   * 隐藏修改密码模态框
   */
  hideChangePasswordModal() {
    document.getElementById('change-password-modal').classList.add('hidden');
  }

  /**
   * 修改密码
   */
  async changePassword() {
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;

    // 验证输入
    if (!currentPassword || !newPassword || !confirmPassword) {
      notification.warning('请填写所有密码字段');
      return;
    }

    if (newPassword.length < 6) {
      notification.warning('新密码至少需要6个字符');
      return;
    }

    if (newPassword !== confirmPassword) {
      notification.warning('两次输入的新密码不一致');
      return;
    }

    if (currentPassword === newPassword) {
      notification.warning('新密码不能与当前密码相同');
      return;
    }

    try {
      const response = await api.put('/user/password', {
        currentPassword: currentPassword,
        newPassword: newPassword
      });

      if (response.success) {
        this.hideChangePasswordModal();
        notification.success('密码修改成功，请重新登录');
        
        // 延迟跳转到登录页面
        setTimeout(() => {
          auth.logout();
          window.location.href = '/login.html';
        }, 2000);
      } else {
        notification.error(response.message || '密码修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      notification.error('修改密码失败');
    }
  }

  /**
   * 处理头像选择
   */
  handleAvatarSelect(file) {
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      notification.error('请选择图片文件');
      return;
    }

    // 验证文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      notification.error('头像文件不能超过5MB');
      return;
    }

    this.avatarFile = file;
    this.showCropModal();
  }

  /**
   * 初始化裁剪画布
   */
  initCropCanvas() {
    this.cropCanvas = document.getElementById('crop-canvas');
    this.cropContext = this.cropCanvas.getContext('2d');
    
    // 设置画布大小
    this.cropCanvas.width = 300;
    this.cropCanvas.height = 300;
  }

  /**
   * 显示裁剪模态框
   */
  showCropModal() {
    if (!this.avatarFile) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      this.cropImage = new Image();
      this.cropImage.onload = () => {
        this.resetCropData();
        this.drawCropPreview();
        document.getElementById('avatar-crop-modal').classList.remove('hidden');
      };
      this.cropImage.src = e.target.result;
    };
    reader.readAsDataURL(this.avatarFile);
  }

  /**
   * 隐藏裁剪模态框
   */
  hideCropModal() {
    document.getElementById('avatar-crop-modal').classList.add('hidden');
    this.avatarFile = null;
    this.cropImage = null;
  }

  /**
   * 重置裁剪数据
   */
  resetCropData() {
    if (!this.cropImage) return;

    const canvasSize = 300;
    const imageAspect = this.cropImage.width / this.cropImage.height;
    
    if (imageAspect > 1) {
      // 宽图
      this.cropData.width = canvasSize;
      this.cropData.height = canvasSize / imageAspect;
    } else {
      // 高图
      this.cropData.width = canvasSize * imageAspect;
      this.cropData.height = canvasSize;
    }
    
    this.cropData.x = (canvasSize - this.cropData.width) / 2;
    this.cropData.y = (canvasSize - this.cropData.height) / 2;
    this.cropData.scale = 1;
    
    document.getElementById('crop-zoom').value = 1;
  }

  /**
   * 更新裁剪缩放
   */
  updateCropScale(scale) {
    this.cropData.scale = scale;
    this.drawCropPreview();
  }

  /**
   * 绘制裁剪预览
   */
  drawCropPreview() {
    if (!this.cropImage || !this.cropContext) return;

    const canvas = this.cropCanvas;
    const ctx = this.cropContext;
    const canvasSize = 300;
    
    // 清空画布
    ctx.clearRect(0, 0, canvasSize, canvasSize);
    
    // 计算缩放后的尺寸
    const scaledWidth = this.cropData.width * this.cropData.scale;
    const scaledHeight = this.cropData.height * this.cropData.scale;
    
    // 居中显示
    const x = (canvasSize - scaledWidth) / 2;
    const y = (canvasSize - scaledHeight) / 2;
    
    // 绘制图片
    ctx.drawImage(this.cropImage, x, y, scaledWidth, scaledHeight);
    
    // 绘制裁剪框
    const cropSize = Math.min(scaledWidth, scaledHeight, 200);
    const cropX = (canvasSize - cropSize) / 2;
    const cropY = (canvasSize - cropSize) / 2;
    
    // 半透明遮罩
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(0, 0, canvasSize, canvasSize);
    
    // 清除裁剪区域
    ctx.globalCompositeOperation = 'destination-out';
    ctx.beginPath();
    ctx.arc(canvasSize / 2, canvasSize / 2, cropSize / 2, 0, 2 * Math.PI);
    ctx.fill();
    
    // 恢复绘制模式
    ctx.globalCompositeOperation = 'source-over';
    
    // 绘制裁剪框边框
    ctx.strokeStyle = '#ffffff';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(canvasSize / 2, canvasSize / 2, cropSize / 2, 0, 2 * Math.PI);
    ctx.stroke();
  }

  /**
   * 保存头像
   */
  async saveAvatar() {
    if (!this.cropImage) return;

    try {
      // 创建最终的头像画布
      const finalCanvas = document.createElement('canvas');
      const finalCtx = finalCanvas.getContext('2d');
      const avatarSize = 200;
      
      finalCanvas.width = avatarSize;
      finalCanvas.height = avatarSize;
      
      // 计算裁剪参数
      const canvasSize = 300;
      const scaledWidth = this.cropData.width * this.cropData.scale;
      const scaledHeight = this.cropData.height * this.cropData.scale;
      const x = (canvasSize - scaledWidth) / 2;
      const y = (canvasSize - scaledHeight) / 2;
      
      const cropSize = Math.min(scaledWidth, scaledHeight, 200);
      const cropX = (canvasSize - cropSize) / 2;
      const cropY = (canvasSize - cropSize) / 2;
      
      // 计算源图像的裁剪区域
      const sourceX = (cropX - x) / this.cropData.scale;
      const sourceY = (cropY - y) / this.cropData.scale;
      const sourceSize = cropSize / this.cropData.scale;
      
      // 绘制裁剪后的头像
      finalCtx.drawImage(
        this.cropImage,
        sourceX, sourceY, sourceSize, sourceSize,
        0, 0, avatarSize, avatarSize
      );
      
      // 转换为Blob
      finalCanvas.toBlob(async (blob) => {
        const formData = new FormData();
        formData.append('avatar', blob, 'avatar.jpg');
        
        try {
          const response = await api.put('/user/avatar', formData);
          
          if (response.success) {
            this.currentUser.avatar = response.avatarUrl;
            this.updateAvatarDisplay();
            this.hideCropModal();
            notification.success('头像更新成功');
          } else {
            notification.error(response.message || '头像更新失败');
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          notification.error('上传头像失败');
        }
      }, 'image/jpeg', 0.9);
      
    } catch (error) {
      console.error('处理头像失败:', error);
      notification.error('处理头像失败');
    }
  }

  /**
   * 显示系统统计信息
   */
  async showSystemStats() {
    try {
      const response = await api.get('/admin/stats');
      
      const stats = response.stats;
      
      // 更新统计显示
      document.getElementById('total-users').textContent = stats.totalUsers || 0;
      document.getElementById('total-storage').textContent = this.formatFileSize(stats.totalStorage || 0);
      document.getElementById('system-uptime').textContent = stats.uptime || '-';
      
    } catch (error) {
      console.error('获取系统统计失败:', error);
      notification.error('获取系统统计失败');
    }
  }

  /**
   * 绑定用户管理模态框事件
   */
  bindUserManagementModals() {
    // 创建用户模态框
    const createUserModal = document.getElementById('create-user-modal');
    const closeCreateUserBtn = document.getElementById('close-create-user-modal');
    const cancelCreateUserBtn = document.getElementById('cancel-create-user-btn');
    const saveCreateUserBtn = document.getElementById('save-create-user-btn');

    [closeCreateUserBtn, cancelCreateUserBtn].forEach(btn => {
      btn.addEventListener('click', () => {
        this.hideCreateUserModal();
      });
    });

    saveCreateUserBtn.addEventListener('click', () => {
      this.createUser();
    });

    // 编辑用户模态框
    const editUserModal = document.getElementById('edit-user-modal');
    const closeEditUserBtn = document.getElementById('close-edit-user-modal');
    const cancelEditUserBtn = document.getElementById('cancel-edit-user-btn');
    const saveEditUserBtn = document.getElementById('save-edit-user-btn');
    const deleteUserBtn = document.getElementById('delete-user-btn');

    [closeEditUserBtn, cancelEditUserBtn].forEach(btn => {
      btn.addEventListener('click', () => {
        this.hideEditUserModal();
      });
    });

    saveEditUserBtn.addEventListener('click', () => {
      this.updateUser();
    });

    deleteUserBtn.addEventListener('click', () => {
      this.showConfirmDeleteModal();
    });

    // 确认删除模态框
    const confirmDeleteModal = document.getElementById('confirm-delete-user-modal');
    const cancelDeleteBtn = document.getElementById('cancel-delete-user-btn');
    const confirmDeleteBtn = document.getElementById('confirm-delete-user-btn');

    cancelDeleteBtn.addEventListener('click', () => {
      this.hideConfirmDeleteModal();
    });

    confirmDeleteBtn.addEventListener('click', () => {
      this.deleteUser();
    });
  }

  /**
   * 加载用户列表
   */
  async loadUsersList() {
    try {
      this.showUsersLoading();
      
      const response = await api.get('/admin/users');
      this.allUsers = response.users || [];
      
      this.renderUsersList(this.allUsers);
      this.showSystemStats(); // 同时更新统计信息
      
    } catch (error) {
      console.error('加载用户列表失败:', error);
      notification.error('加载用户列表失败');
      this.showUsersEmptyState();
    } finally {
      this.hideUsersLoading();
    }
  }

  /**
   * 渲染用户列表
   */
  renderUsersList(users) {
    const tbody = document.getElementById('users-table-body');
    
    if (!users || users.length === 0) {
      this.showUsersEmptyState();
      return;
    }

    this.hideUsersEmptyState();
    
    tbody.innerHTML = users.map(user => {
      const storageUsed = user.storage_used || 0;
      const storageLimit = user.storage_limit || 0;
      const storagePercentage = storageLimit > 0 ? (storageUsed / storageLimit) * 100 : 0;
      
      return `
        <tr class="border-b border-neutral-100 hover:bg-neutral-50">
          <td class="p-3">
            <div class="flex items-center gap-3">
              <div class="w-8 h-8 bg-neutral-300 rounded-full flex items-center justify-center overflow-hidden">
                ${user.avatar ? 
                  `<img src="${user.avatar}" alt="头像" class="w-full h-full object-cover">` :
                  '<i class="fa fa-user text-neutral-500 text-sm"></i>'
                }
              </div>
              <div>
                <div class="font-medium text-neutral-800">${user.nickname}</div>
                <div class="text-sm text-neutral-600">${user.email}</div>
              </div>
            </div>
          </td>
          <td class="p-3">
            <span class="px-2 py-1 text-xs rounded-full ${user.role === 'admin' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'}">
              ${user.role === 'admin' ? '管理员' : '用户'}
            </span>
          </td>
          <td class="p-3">
            <div class="text-sm text-neutral-800">${this.formatFileSize(storageUsed)} / ${this.formatFileSize(storageLimit)}</div>
            <div class="w-full bg-neutral-200 rounded-full h-1 mt-1">
              <div class="h-1 rounded-full ${storagePercentage >= 90 ? 'bg-red-500' : storagePercentage >= 80 ? 'bg-yellow-500' : 'bg-blue-500'}" 
                   style="width: ${Math.min(storagePercentage, 100)}%"></div>
            </div>
          </td>
          <td class="p-3 text-sm text-neutral-600">
            ${new Date(user.created_at).toLocaleDateString('zh-CN')}
          </td>
          <td class="p-3">
            <button class="edit-user-btn btn-icon w-8 h-8" data-user-id="${user.id}" title="编辑用户">
              <i class="fa fa-edit text-neutral-500"></i>
            </button>
          </td>
        </tr>
      `;
    }).join('');

    // 绑定编辑按钮事件
    tbody.querySelectorAll('.edit-user-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const userId = parseInt(e.currentTarget.dataset.userId);
        this.showEditUserModal(userId);
      });
    });
  }

  /**
   * 过滤用户
   */
  filterUsers(searchTerm) {
    if (!this.allUsers) return;
    
    const filteredUsers = this.allUsers.filter(user => 
      user.nickname.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    this.renderUsersList(filteredUsers);
  }

  /**
   * 显示创建用户模态框
   */
  showCreateUserModal() {
    // 清空表单
    document.getElementById('create-user-email').value = '';
    document.getElementById('create-user-nickname').value = '';
    document.getElementById('create-user-password').value = '';
    document.getElementById('create-user-role').value = 'user';
    document.getElementById('create-user-storage-limit').value = '30';
    
    document.getElementById('create-user-modal').classList.remove('hidden');
  }

  /**
   * 隐藏创建用户模态框
   */
  hideCreateUserModal() {
    document.getElementById('create-user-modal').classList.add('hidden');
  }

  /**
   * 创建用户
   */
  async createUser() {
    const email = document.getElementById('create-user-email').value.trim();
    const nickname = document.getElementById('create-user-nickname').value.trim();
    const password = document.getElementById('create-user-password').value;
    const role = document.getElementById('create-user-role').value;
    const storageLimit = parseInt(document.getElementById('create-user-storage-limit').value);

    // 验证输入
    if (!email || !nickname || !password) {
      notification.warning('请填写所有必填字段');
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      notification.warning('请输入有效的邮箱地址');
      return;
    }

    if (password.length < 6) {
      notification.warning('密码至少需要6个字符');
      return;
    }

    if (storageLimit < 1 || storageLimit > 100) {
      notification.warning('存储限制必须在1-100GB之间');
      return;
    }

    try {
      const response = await api.post('/admin/users', {
        email,
        nickname,
        password,
        role,
        storageLimit: storageLimit * 1024 * 1024 * 1024 // 转换为字节
      });

      if (response.success) {
        notification.success('用户创建成功');
        this.hideCreateUserModal();
        this.loadUsersList(); // 刷新用户列表
      } else {
        notification.error(response.message || '创建用户失败');
      }
    } catch (error) {
      console.error('创建用户失败:', error);
      notification.error('创建用户失败');
    }
  }

  /**
   * 显示编辑用户模态框
   */
  showEditUserModal(userId) {
    const user = this.allUsers.find(u => u.id === userId);
    if (!user) return;

    document.getElementById('edit-user-id').value = user.id;
    document.getElementById('edit-user-email').value = user.email;
    document.getElementById('edit-user-nickname').value = user.nickname;
    document.getElementById('edit-user-role').value = user.role;
    document.getElementById('edit-user-storage-limit').value = Math.round((user.storage_limit || 0) / (1024 * 1024 * 1024));
    document.getElementById('edit-user-password').value = '';

    document.getElementById('edit-user-modal').classList.remove('hidden');
  }

  /**
   * 隐藏编辑用户模态框
   */
  hideEditUserModal() {
    document.getElementById('edit-user-modal').classList.add('hidden');
  }

  /**
   * 更新用户
   */
  async updateUser() {
    const userId = parseInt(document.getElementById('edit-user-id').value);
    const nickname = document.getElementById('edit-user-nickname').value.trim();
    const role = document.getElementById('edit-user-role').value;
    const storageLimit = parseInt(document.getElementById('edit-user-storage-limit').value);
    const password = document.getElementById('edit-user-password').value;

    // 验证输入
    if (!nickname) {
      notification.warning('请输入用户昵称');
      return;
    }

    if (storageLimit < 1 || storageLimit > 100) {
      notification.warning('存储限制必须在1-100GB之间');
      return;
    }

    if (password && password.length < 6) {
      notification.warning('密码至少需要6个字符');
      return;
    }

    try {
      const updateData = {
        nickname,
        role,
        storageLimit: storageLimit * 1024 * 1024 * 1024 // 转换为字节
      };

      if (password) {
        updateData.password = password;
      }

      const response = await api.put(`/admin/users/${userId}`, updateData);

      if (response.success) {
        notification.success('用户信息更新成功');
        this.hideEditUserModal();
        this.loadUsersList(); // 刷新用户列表
      } else {
        notification.error(response.message || '更新用户失败');
      }
    } catch (error) {
      console.error('更新用户失败:', error);
      notification.error('更新用户失败');
    }
  }

  /**
   * 显示确认删除模态框
   */
  showConfirmDeleteModal() {
    const userId = parseInt(document.getElementById('edit-user-id').value);
    const user = this.allUsers.find(u => u.id === userId);
    if (!user) return;

    document.getElementById('delete-user-name').textContent = user.nickname;
    document.getElementById('confirm-delete-user-modal').classList.remove('hidden');
  }

  /**
   * 隐藏确认删除模态框
   */
  hideConfirmDeleteModal() {
    document.getElementById('confirm-delete-user-modal').classList.add('hidden');
  }

  /**
   * 删除用户
   */
  async deleteUser() {
    const userId = parseInt(document.getElementById('edit-user-id').value);

    try {
      const response = await api.delete(`/admin/users/${userId}`);

      if (response.success) {
        notification.success('用户删除成功');
        this.hideConfirmDeleteModal();
        this.hideEditUserModal();
        this.loadUsersList(); // 刷新用户列表
      } else {
        notification.error(response.message || '删除用户失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      notification.error('删除用户失败');
    }
  }

  /**
   * 显示用户加载状态
   */
  showUsersLoading() {
    document.getElementById('users-loading').classList.remove('hidden');
    document.getElementById('users-empty-state').classList.add('hidden');
  }

  /**
   * 隐藏用户加载状态
   */
  hideUsersLoading() {
    document.getElementById('users-loading').classList.add('hidden');
  }

  /**
   * 显示用户空状态
   */
  showUsersEmptyState() {
    document.getElementById('users-empty-state').classList.remove('hidden');
    document.getElementById('users-loading').classList.add('hidden');
  }

  /**
   * 隐藏用户空状态
   */
  hideUsersEmptyState() {
    document.getElementById('users-empty-state').classList.add('hidden');
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 显示加载状态
   */
  showLoading() {
    document.getElementById('loading').classList.remove('hidden');
  }

  /**
   * 隐藏加载状态
   */
  hideLoading() {
    document.getElementById('loading').classList.add('hidden');
  }
}

// 初始化个人中心
document.addEventListener('DOMContentLoaded', () => {
  // 检查用户认证
  if (!auth.isAuthenticated()) {
    window.location.href = '/login.html';
    return;
  }
  
  window.profileManager = new ProfileManager();
});